package com.sxl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.sxl.annotation.NoToken;
import com.sxl.config.LayUiResult;
import com.sxl.config.TokenUtil;
import com.sxl.domain.MenuInfo;
import com.sxl.domain.Userroles;
import com.sxl.domain.Users;
import com.sxl.mapper.UserrolesMapper;
import com.sxl.mapper.UsersMapper;
import com.sxl.service.ModulesService;
import com.sxl.service.UserrolesService;
import com.sxl.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import java.util.List;
import java.util.Map;

/**
 * @ProjectName: CRMProject
 * @Package: com.sxl.controller
 * @Author songxueliang
 * @Date 2022/4/16 10:54
 */
@RestController
@CrossOrigin
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ModulesService modulesService;
    @Autowired
    private UserrolesMapper userrolesMapper;
//    private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//    private String dqsj = df.format(new Date());

    /**
     * 登录
     *
     * @param users
     * @return
     */
    @PostMapping("/login")
    @NoToken
    public Map<String, Object> login(Users users) {
        String md5Password=DigestUtils.md5DigestAsHex(users.getPassword().getBytes());
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("loginName", users.getLoginName());
        Users u = usersService.getOne(wrapper);
        if (u == null) {
            return LayUiResult.toClient("1", "用户名不存在");
        }
        if (u.getIsLockout() != 0) {
            return LayUiResult.toClient("1", "账户已锁定");
        }
        QueryWrapper<Users> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("loginName", users.getLoginName())
                .eq("password", md5Password);
        Users usersPassword = usersService.getOne(wrapper1);
        if (usersPassword == null) {
            if (!u.getLoginName().equals("admin")) {
                String count = (String) redisTemplate.opsForValue().get(users.getLoginName());//从redis取错误次数
                if (StringUtils.isBlank(count)) {
                    //取不到,赋值1
                    count = "1";
                } else {
                    count = (Integer.parseInt(count) + 1) + "";
                }
                redisTemplate.opsForValue().set(users.getLoginName(), count);
                if (Integer.parseInt(count) == 3) {

                    UpdateWrapper<Users> usersUpdateWrapper = new UpdateWrapper<>();
                    usersUpdateWrapper.set("isLockOut", 1)
                            .eq("loginName", users.getLoginName());
                    usersService.update(usersUpdateWrapper);
                    redisTemplate.delete(users.getLoginName());
                }
                if (usersPassword == null) {
                    usersService.updatePsdwrongTimeById(u.getId());
                    return LayUiResult.toClient("1", "密码输入错误,当前第" + count + "次,3次后自动锁定");
                }
            }else {
                return LayUiResult.toClient("1", "密码输入错误");
            }
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dqsj = df.format(new Date());
        UpdateWrapper<Users> updateWrapper=new UpdateWrapper<>();
        updateWrapper.set("lastLoginTime",dqsj).eq("id",usersPassword.getId());
        usersService.update(updateWrapper);
        List<MenuInfo> opsList = modulesService.initMenu(usersPassword.getId(), "n");
        String btnPermission = "";
        for (MenuInfo m : opsList) {
            btnPermission += m.getOps() + "|";
        }
        System.out.println(btnPermission);
        String token = "";
        if (usersPassword != null) {
            //生成token
            try {
                token = TokenUtil.sign(u, 60 * 30 * 1000);
            } catch (UnsupportedEncodingException | JsonProcessingException e) {
                e.printStackTrace();
            }
        } else {
            LayUiResult.toClient("1", "登录失败");
        }
        Map<String, Object> rslmap = new HashMap<>();
        rslmap.put("code", "0");
        rslmap.put("msg", "登录成功");
        rslmap.put("token", token);
        rslmap.put("userId", usersPassword.getId());
        rslmap.put("btnPermission", btnPermission);
        rslmap.put("loginName", usersPassword.getLoginName());
        return rslmap;
    }

    /**
     * 主页查询
     *
     * @param users
     * @return
     */
    @GetMapping
    public Map<String, Object> selectAllUsers(Users users) {
        List<Users> list = usersService.selectAll(users);
        int count = usersService.getCount(users);
        return LayUiResult.toClient("0", "成功", count, list);
    }

    /**
     * 处理开关
     * 是否锁定
     *
     * @return
     */
    @PostMapping("/switchIsLockout")
    public Map<String, Object> switchIsLockout(Users users) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dqsj = df.format(new Date());
        int num = users.getValid().equals("on") ? 1 : 0;
        Users users1 = usersMapper.selectById(users.getId());
        if (users1.getLoginName().equals("admin")){
            return LayUiResult.toClient("1","管理员账户不可被锁定");
        }
        if (num == 1) {
            users.setLockTime(dqsj);
        }
        users.setIsLockout(num);
        boolean rel = usersService.updateById(users);
        return rel == true ? LayUiResult.toClient("0", "修改成功") : LayUiResult.toClient("1", "修改失败");
    }

    /**
     * 添加用户
     *
     * @param users
     * @return
     */
    @PostMapping("/insertUsers")
    public Map<String, Object> insertUsers(Users users) {
        List<Users> list = usersService.list();
        for (int i = 0; i < list.size(); i++) {
            if (users.getLoginName().equals(list.get(i).getLoginName())) {
                return LayUiResult.toClient("1", "已有用户使用此用户名");
            }
        }
        if(users.getPassword()!=null && users.getPassword()!=""){
            String md5Password=DigestUtils.md5DigestAsHex(users.getPassword().getBytes());
            users.setPassword(md5Password);
        }
        Boolean rel = usersService.save(users);
        return rel == true ? LayUiResult.toClient("0", "添加成功") : LayUiResult.toClient("1", "添加失败");
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteById(@PathVariable Integer id) {
        Users users = usersMapper.selectById(id);
        if (users.getLoginName().equals("admin")){
            return LayUiResult.toClient("1","管理员账户不可被删除");
        }
        QueryWrapper<Userroles> wrapper = new QueryWrapper<>();
        wrapper.eq("userId",id);
        List<Userroles> userroles = userrolesMapper.selectList(wrapper);
        if(userroles.size()!=0){
            return LayUiResult.toClient("1","该用户下还有角色未移除");
        }
        boolean rel = usersService.removeById(id);
        return rel == true ? LayUiResult.toClient("0", "删除成功") : LayUiResult.toClient("1", "删除失败");
    }

    /**
     * 修改用户信息
     *
     * @param users
     * @return
     */
    @PostMapping("/updateById")
    public Map<String, Object> updateById(Users users) {
        Boolean rel = usersService.updateById(users);
        return rel == true ? LayUiResult.toClient("0", "修改成功") : LayUiResult.toClient("1", "修改失败");
    }

    /**
     * 重置密码
     *
     * @param users
     * @return
     */
    @PostMapping("/updatePasswordById")
    public Map<String, Object> updatePasswordById(Users users) {
        String password = "ysd123";
        String md5Password=DigestUtils.md5DigestAsHex(password.getBytes());
        users.setPassword(md5Password);
        Users users1 = usersMapper.selectById(users.getId());
        if (users1.getLoginName().equals("admin")){
            return LayUiResult.toClient("1","管理员账户不可被重置密码");
        }
        boolean rel = usersService.updateById(users);
        return rel == true ? LayUiResult.toClient("0", "重置密码成功") : LayUiResult.toClient("1", "重置密码失败");
    }
    /**
     * 修改密码
     */
    @PostMapping("updatePassword")
    public Map<String,Object> updatePassword(String password,Integer id,String old_password,String new_password){
        password=DigestUtils.md5DigestAsHex(password.getBytes());
        old_password=DigestUtils.md5DigestAsHex(old_password.getBytes());
        new_password=DigestUtils.md5DigestAsHex(new_password.getBytes());
        Users users = usersMapper.selectById(id);
        if (!old_password.equals(users.getPassword())){
            return LayUiResult.toClient("1","旧密码输入错误");
        }
        if (!new_password.equals(password)){
            return LayUiResult.toClient("1","两次新密码输入不一致");
        }
        if (new_password.equals(old_password)){
            return LayUiResult.toClient("1","新密码不能与旧密码相同");
        }
        UpdateWrapper<Users> updateWrapper=new UpdateWrapper<>();
        updateWrapper.set("password",password)
                .eq("id",id);
        boolean rel = usersService.update(updateWrapper);
        return rel == true ? LayUiResult.toClient("0", "修改密码成功") : LayUiResult.toClient("1", "修改密码失败");
    }
}

